/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-09-02 14:15
 */

package main

//对数据进行操作
import (
	"errors"
	"time"
)

const TASK_FIELDS  string="id,title,url,cron,request_type,timeout,save_body"

type Task struct {
	Id          int
	Title       string
	Url         string
	Cron        string
	RequestType string `db:"request_type"`
	Timeout     int
	SaveBody    string `db:"save_body"`
}

type TaskList []*Task

func NewTask() *Task {
	return new(Task)
}

func GetTask() *Task{
	return task.Get().(*Task)
}

func PutTask(t *Task){
	task.Put(t)
}

func (t *Task) Find(id int) (*Task, error) {
	err := sql.FindScanStruct(t, `select `+TASK_FIELDS+` from __TASK__ where status=1 and id=?`, id)
	if err != nil {
		Log.Debug("获取任务信息失败：%s", err)
		return nil, errors.New("获取任务信息失败")
	}
	return t, nil
}

func (t *Task) GetListAll() TaskList {
	var list = make(TaskList, 0)
	err := sql.QueryScanStructs(&list, `select `+TASK_FIELDS+` from __TASK__ where status=1`)
	if err != nil {
		Log.Debug("获取任务列表失败：%s", err)
		return nil
	}
	return list
}

/**
写入请求日志
status_code 返回状态码
e_time 响应时间 单位毫秒
body 请求返回的内容
err_info 错误信息
*/
func write_log(task_id int, status_code int, e_time int64, body string, err_info string) {
	create_time := time.Now().Unix()
	_, err := sql.Insert(`insert into __TASK_RECORD__ 
	(task_id,status_code,exe_time,err_info,return_body,create_time) 
	values(?,?,?,?,?,?)`, task_id, status_code, e_time, err_info, body, create_time)
	if err != nil {
		Log.Notice("[%d]请求记录写入失败:%s", task_id, err)
	}
}
